package com.didispace.domain;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description:
 * @Author: MaGuoDong
 * @Date: Created in 2018/7/25 16:17
 * @company 蜂网供应链管理（上海）有限公司
 */
public class BoundedBuffer {
    final Lock lock = new ReentrantLock();//锁对象
    final Condition notFull = lock.newCondition();//写线程条件
    final Condition notEmpty = lock.newCondition();//读线程条件

    final Object [] items = new Object[100]; //缓存队列
    int putptr/*写索引*/, takeptr/*读索引*/, count/*队列中存在的数据个数*/;

    public void put(Object x) throws InterruptedException {
         lock.lock();
         try {
             while (count == items.length) {
                 notFull.await();
             }
             items[putptr] = x;
             if (++putptr == items.length) {//如果写索引写到了队列的最后一个位置了，那么设置为0
                 putptr = 0;
             }
             ++count;
             notEmpty.signal();//唤醒读线程
         }finally {
             lock.unlock();
         }
    }
    public Object take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0) {
                notEmpty.await();
            }
           Object x = items[takeptr] ;//取值
            if(++takeptr == items.length){
                takeptr = 0;
            }
            --count;
            notFull.signal();//唤醒写线程
            return x;
        }finally {
            lock.unlock();
        }
    }
}
